package com.jeesite.modules.aliyun.msg.service;

import com.alibaba.fastjson.JSON;
import com.jeesite.common.lang.ExceptionUtils;
import com.jeesite.common.lang.ObjectUtils;
import com.jeesite.common.mapper.JsonMapper;
import com.jeesite.common.service.BaseService;
import com.jeesite.modules.aliyun.msg.AliyunSmsUtils;
import com.jeesite.modules.msg.entity.MsgPush;
import com.jeesite.modules.msg.entity.content.SmsMsgContent;
import com.jeesite.modules.msg.send.MsgSendService;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

/**
 * 短信发送服务实现
 * @author hzy
 * @version 2019年12月17日
 */
@Service
public class CustomSmsSendService extends BaseService implements MsgSendService {

    @Override
    public void sendMessage(MsgPush msgPush) {
        try{
            // 发送短信
            SmsMsgContent content = msgPush.parseMsgContent(SmsMsgContent.class);
            Map<String, Object> tplData = content.getTplData();
            String result = AliyunSmsUtils.sendByTemplate(msgPush.getReceiveCode(), content.getTplKey(), JSON.toJSONString(tplData));
            Map<String, Object> map = JsonMapper.fromJson(result, Map.class);
            // 发送成功
            if (ObjectUtils.toInteger(map.get("result")) == 0){
                msgPush.setPushStatus(MsgPush.PUSH_STATUS_SUCCESS);
                msgPush.addPushReturnContent(result);
            }
            // 发送失败
            else{
                throw new RuntimeException(result);
            }

        } catch (Exception ex) {
            logger.error("发送短信失败！ ", ex);
            msgPush.setPushDate(new Date());
            msgPush.setPushStatus(MsgPush.PUSH_STATUS_FAIL);
            msgPush.addPushReturnContent(ExceptionUtils.getStackTraceAsString(ex));
        }
    }
}
